#coding:utf-8
'''
Created on 2017-10-12

@author: sandy
'''
import json
import logging
import os
from pycommon import const
class Account(object):
    
    def __init__(self):
        self.account = u""
        self.password = u''
        self.cfglist = []
        self.cfgpath = []
        pass
    
    def __str__(self):
        return "account={0} passwd={1} cfglist={2}".format(self.account,self.password,str(self.cfglist))

    def parse(self,jf):
        self.cfglist = []
        self.cfgpath = []
        self.account = jf.get("account")
        self.password = jf.get("password")
        self.cfglist = jf.get("cfglist",[])
        dirs = self.cfglist
        for curdir in dirs:
            for li in os.listdir(curdir):
                filePathStr = os.path.join(curdir,li)
                self.cfgpath.append(filePathStr)
        pass

    pass

class AccountConfig(object):
    def __init__(self):
        self.rundir = os.path.dirname(__file__)
        self.accounts = {}
        self.sessions = {}
        pass
    
    def loadFromFile(self):
        cf = json.load(file(os.path.join(self.rundir,"accountconfig","account.json")), encoding='utf-8')
        self.loadFromJson(cf)

    def loadFromJson(self,cf):
        self.accounts = {}
        for jf in cf:
            ac = Account()
            ac.parse(jf)
            self.accounts[ac.account] = ac

    def checkAccount(self,account,passwd):
        code = const.ERR_OK
        ac = self.accounts.get(account,None)
        if not ac:
            code = const.ERR_ACCOUNT_NOT_EXIST
        else:
            if ac and ac.password != passwd:
                code = const.ERR_PASSWD_WRONG
            else:
                code = const.ERR_OK
        return code


    def checkCfgNamePermissions(self,account,cfgname):
        ac = self.accounts.get(account,None)
        cfgpath = ac.cfgpath if ac else []
        return cfgname in cfgpath
        pass

    ####### Session 相关
    def addSession(self,account,session):
        self.sessions[session] = account

    def getAccount(self,session):
        return self.sessions.get(session,"")
    
    def checkSession(self,session):
        return self.getAccount(session) != ""

    def getCfgListBySession(self,session):
        account = self.getAccount(session)
        if account != "":
            ac = self.accounts.get(account,None)
            return ac.cfglist if ac else []
        else:
            return []



instance = AccountConfig()